package com.njwb.Swing.Users;

import com.njwb.Util.UtilService;
import com.njwb.pojo.Users;

import javax.swing.*;
import java.awt.*;

public class EditUserDialog extends JDialog {
    private JTextField usernameField, passwordField, genderField, ageField, phoneField, addressField;
    private JComboBox<String> roleBox;
    private JButton confirmButton, cancelButton;
    private UtilService utilService;
    private Users user;
    private Runnable refreshCallback;

    public EditUserDialog(Frame owner, UtilService utilService, Users user, Runnable refreshCallback) {
        super(owner, "修改用户", true);
        this.utilService = utilService;
        this.user = user;
        this.refreshCallback = refreshCallback;

        setSize(400, 350);
        setLocationRelativeTo(owner);
        setLayout(new GridLayout(8, 2, 5, 5));

        add(new JLabel("用户名:")); usernameField = new JTextField(user.getUsername()); add(usernameField);
        add(new JLabel("密码:")); passwordField = new JTextField(user.getPassword()); add(passwordField);
        add(new JLabel("性别:")); genderField = new JTextField(user.getGender()); add(genderField);
        add(new JLabel("年龄:")); ageField = new JTextField(String.valueOf(user.getAge())); add(ageField);
        add(new JLabel("电话:")); phoneField = new JTextField(user.getPhone()); add(phoneField);
        add(new JLabel("地址:")); addressField = new JTextField(user.getAddress()); add(addressField);
        add(new JLabel("身份:")); roleBox = new JComboBox<>(new String[]{"普通用户", "管理员"}); roleBox.setSelectedIndex(user.getRole()); add(roleBox);

        confirmButton = new JButton("确认"); cancelButton = new JButton("取消");
        add(confirmButton); add(cancelButton);

        confirmButton.addActionListener(e -> {
            try {
                String username = usernameField.getText().trim();
                String password = passwordField.getText().trim();
                String gender = genderField.getText().trim();
                int age = Integer.parseInt(ageField.getText().trim());
                String phone = phoneField.getText().trim();
                String address = addressField.getText().trim();
                int role = roleBox.getSelectedIndex();

                boolean success = utilService.updateUser(user.getId(), username, password, gender, age, phone, address, role);
                if (success) {
                    JOptionPane.showMessageDialog(this, "修改成功！");
                    dispose();
                    if (refreshCallback != null) refreshCallback.run();
                } else {
                    JOptionPane.showMessageDialog(this, "修改失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "输入数据有误！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dispose());
    }
}
